package com.znow.admin.filter;

import com.alibaba.fastjson.JSON;
import com.znow.admin.system.security.config.SysConfig;
import com.znow.admin.system.security.enums.SysUserErrorEnums;
import com.znow.admin.system.security.model.dto.SysUserDetailsDTO;
import com.znow.common.model.CommonResult;
import com.znow.common.utils.jwt.JwtTokenUtils;
import com.znow.common.utils.request.RequestUtils;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.web.authentication.WebAuthenticationDetailsSource;
import org.springframework.security.web.util.matcher.AntPathRequestMatcher;
import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * jwt身份验证令牌过滤器
 *
 * @author Nemo
 * @date 2022/09/29
 */
@Slf4j
@Component
@AllArgsConstructor
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {

    private final UserDetailsService userDetailsService;

    private final SysConfig sysConfig;

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
            throws ServletException, IOException {
        final String token = RequestUtils.resolveToken(request);
        // 过滤不需要认证的url
        if (!requiresAuthentication(request)) {
            chain.doFilter(request, response);
            return;
        }
        // 如果token为空
        if (StringUtils.isBlank(token)) {
            tokenIsNullReturnError(request, response);
            return;
        }
        // 校验token是否过期
        if (!JwtTokenUtils.validateToken(token)) {
            tokenExpiredReturnError(request, response);
            return;
        }
        final SysUserDetailsDTO userDTO = JwtTokenUtils.getSubject(token, SysUserDetailsDTO.class);
        if (userDTO != null) {
            if (SecurityContextHolder.getContext().getAuthentication() == null) {
                SysUserDetailsDTO userDetails = (SysUserDetailsDTO) this.userDetailsService
                        .loadUserByUsername(userDTO.getUsername());
                userDetails.setToken(token);
                UsernamePasswordAuthenticationToken authentication = new UsernamePasswordAuthenticationToken(
                        userDetails, null, userDetails.getAuthorities());
                authentication.setDetails(new WebAuthenticationDetailsSource().buildDetails(request));
                SecurityContextHolder.getContext().setAuthentication(authentication);
            }
        }
        chain.doFilter(request, response);
    }

    /**
     * 获取需要身份验证的url
     *
     * @param request 请求
     * @return boolean
     */
    protected boolean requiresAuthentication(HttpServletRequest request) {
        for (String item : sysConfig.getIgnoreUrl()) {
            if (new AntPathRequestMatcher(item).matches(request)) {
                return false;
            }
        }
        return true;
    }

    /**
     * 令牌过期返回错误
     *
     * @param request  请求
     * @param response 响应
     */
    private void tokenExpiredReturnError(HttpServletRequest request, HttpServletResponse response) {
        final CommonResult<?> failed = CommonResult.failed(SysUserErrorEnums.ACCOUNT_TOKEN_EXPIRE);
        // token过期
        RequestUtils.responseJson(JSON.toJSONString(failed), request, response);
    }

    private void tokenIsNullReturnError(HttpServletRequest request, HttpServletResponse response) {
        final CommonResult<?> failed = CommonResult.failed(SysUserErrorEnums.ACCOUNT_NEED_LOGIN);
        // token过期
        RequestUtils.responseJson(JSON.toJSONString(failed), request, response);
    }

}
